

/**
 * @Author: 陈瑞鹏
 * @Date:   2023-01-03 11:06:17
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-01-04 15:40:39
 */
import gameCtr from "../ctrs/gameCtr";
import { limit } from "../libs/core/utils";
import { gameConfig } from "../shared/game/gameConfig";
import { ArrowState } from "../shared/game/state/ArrowState";

const { ccclass, property } = cc._decorator;
@ccclass
export default class timeArrow extends cc.Component {

  id!: number;
  state!: ArrowState;

  @property(cc.Node)
  arrow!: cc.Node;

  @property({ type: cc.Sprite, tooltip: "贴图" })
  sp: cc.Sprite = null;

  @property({ type: cc.Animation, tooltip: "动画" })
  ani: cc.Animation = null;

  // 开始位置（场景坐标）
  private _startPos: cc.Vec2;
  // 落点位置（场景坐标）
  private _endPos: cc.Vec2;
  // 开始时间（场景时间）
  private _startTime = 0;
  // 结束时间（场景时间）
  private _endTime = 0;

  private ARROW_TOP = 0;

  init(state: ArrowState, now: number) {
    this.id = state.id;
    this.state = state;
    console.log(this.state);
    this.node.setPosition(cc.v3(state.startPos.x, state.startPos.y));
    this._startPos = cc.v2(state.startPos.x, state.startPos.y);
    this._endPos = cc.v2(state.targetPos.x, state.targetPos.y);
    this._startTime = Date.now();
    // 箭的展示与判定相分离，展示就按固定的飞行时长展示
    this._endTime = state.targetTime;

    this.ARROW_TOP = 3;

    cc.resources.load("bullets/" + state.arrowType, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
      if (err) return;
      this.sp.spriteFrame = sp;
    })

    this._updatePosAndForward(0);
  }

  update() {
    //下一个目标位置
    let percent = limit((Date.now() - this._startTime) / (this._endTime - this._startTime), 0, 1);
    // console.log(percent, "percent")
    this._updatePosAndForward(percent);

    if (percent >= 1) {
      this.remove();
    }
  }

  private _isRemoved = false;
  remove() {
    if (this._isRemoved) {
      return;
    }
    this._isRemoved = true;

    // 落地 1 秒后消失
    // this.scheduleOnce(() => {
    // this.node.removeFromParent()
    this.ani.node.active = true;
    this.ani.stop();
    this.ani.play("baozha");
    this.ani.once("finished", this.recover, this);
    // }, 1)
  }

  recover() {
    this._isRemoved = false;
    this.ani.node.active = false;
    gameCtr.ins.poolObj['timeArrow'].put(this.node);
  }



  private _updatePosAndForward(percent: number) {
    let nextPos = this._getPos(percent);
    this.arrow.setPosition(nextPos);
    // console.log("nextPos");
    // console.log(nextPos);
    //武器朝向下一个目标位置, 形成曲线飞行的感觉
    let lastPos = this._getPos(percent - 0.01)
    this.arrow.forward = nextPos.clone().subtract(lastPos).normalize();
  }

  private _getPos(percent: number) {
    let p = cc.v2(this._endPos.x - this._startPos.x, this._endPos.y - this._startPos.y);
    let pos = cc.v2(this._startPos.x + percent * p.x, this._startPos.y + percent * p.y);
    // console.log(pos);
    // pos.y = this.ARROW_TOP * Math.cos(percent * Math.PI - Math.PI / 2);
    return cc.v3(pos);
  }
}